import { ref , watchEffect, unref } from 'vue'
import { ElMessage } from 'element-plus'

// 按照惯例，组合式函数名以“use”开头
export function usePage(reactiveObject) {
  // 被组合式函数封装和管理的状态
   const loading = ref(true);
   const total = ref(0);
   const rows = ref([]);
   //表格选中的主键
   const ids = ref([]);
   //是否允许修改
   const single = ref(true);
   //是否允许删除
   const multiple = ref(true);
    
  const data = reactive({
    queryParams: {
      page: 1,
      size: 10
    } 
  });

  const { queryParams} = toRefs(data);
  
  
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.page = 1; 
    getList();
  }
  /** 重置按钮操作 */
  function resetQuery() {
    const {proxy} =unref(reactiveObject) 
    if (proxy.$refs["queryFormRef"]) {
        proxy.$refs["queryFormRef"].resetFields();
    } 
    handleQuery();
  }
  
  //当每页多少笔更改了
   function handleSizeChange(val) {
     queryParams.value.page=1
     queryParams.value.size =val
     getList();
  }
  
  //当前页发化娈化
  function handleCurrentChange(val) {
      queryParams.value.page=value
      getList();
  }
   
   //获取分页数据
   function getList(){
     loading.value = true; 
     const {dataApi} =unref(reactiveObject)
   
     dataApi(queryParams.value).then(resp => {
     
       rows.value = resp.data.rows;
       total.value = resp.data.total;
       loading.value = false;
     });
     // dataApi(queryParams.value).then(resp => {
     //   console.log(resp);
     //   rows.value = resp.data.rows;
     //   total.value = resp.data.total;
     //   loading.value = false;
     // });
   }
 
   // toValue() vue 3.3的版本才有，现在只能使用unref来解决 
   const ro=unref(reactiveObject)       
   if(ro.dataApi instanceof Function){
     getList();
   }else{
    ElMessage.error('必须usePage中定义dataApi查询函数.')
   }  
   
   //table表格选项变化事件
   function handleSelectionChange(selection){
     const {primaryKey} =unref(reactiveObject) 
     if(primaryKey){
       ids.value = selection.map(item => item[primaryKey]); 
       //是否启用编辑
       single.value = selection.length != 1;
       //是否启用删除按钮
       multiple.value = !selection.length;
     }else{
        ElMessage({ message: '请先定义名为primaryKey的主键值',type: 'error'})
     }
     
   }
   

  // 通过返回值暴露所管理的状态
  return { loading, total,rows ,queryParams,ids,single,multiple, handleQuery, resetQuery, handleSizeChange , handleCurrentChange, getList, handleSelectionChange}
}
